package fun.boomcat.luckyhe.mirai.plugin.command;

import fun.boomcat.luckyhe.mirai.plugin.command.utils.OpReplyHelpString;
import fun.boomcat.luckyhe.mirai.plugin.command.utils.thread.ReplyWebThread;
import fun.boomcat.luckyhe.mirai.plugin.config.ConfigOperation;
import fun.boomcat.luckyhe.mirai.plugin.dbutils.ReplyListModifier;
import fun.boomcat.luckyhe.mirai.plugin.dbutils.ServeGroupListModifier;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandOwner;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.RawCommand;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.message.data.MessageChain;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.*;

public class OpReplyCommand extends RawCommand {
//    插件入口的那个对象
    private final JavaPlugin INSTANCE;


    public OpReplyCommand(@NotNull CommandOwner owner, @NotNull String primaryName, @NotNull String[] secondaryNames, @NotNull String usage, @NotNull String description, @NotNull Permission parentPermission, boolean prefixOptional, JavaPlugin INSTANCE) {
        super(owner, primaryName, secondaryNames, usage, description, parentPermission, prefixOptional);
        this.INSTANCE = INSTANCE;
    }

    @Nullable
    @Override
    public Object onCommand(@NotNull CommandSender commandSender, @NotNull MessageChain messageChain, @NotNull Continuation<? super Unit> continuation) {
//        获取指令参数长度，不包括指令本身
        int mcLen = messageChain.toArray().length;

        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        String primaryName = this.getPrimaryName();

        if (mcLen == 0) {
//            无参数，输出帮助

            commandSender.sendMessage(OpReplyHelpString.helpStr(primaryName, getSecondaryNames()));
            return null;
        }

//        第一个参数为选择功能
        String operation = messageChain.get(0).toString();

        switch (operation.toLowerCase()) {
//            分支条件

            case "init":
            case "初始化":
//                初始化数据库操作
                onInit(commandSender);
                break;

            case "pass":
            case "通过":
//                通过一条自动回复操作
                onPassReply(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        getSecondaryNames()
                );
                break;
            case "deny":
            case "拒绝":
//                拒绝一条自动回复操作
                onDenyReply(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        getSecondaryNames()
                );
                break;
            case "alist":
            case "审核列表":
//                显示待审核列表
                onSelectAuditingReplies(commandSender);
                break;

            case "list":
            case "回复列表":
//                显示回复列表
                onListReplies(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        getSecondaryNames()
                );
                break;

            case "groupadd":
            case "群添加":
//                添加服务群
                onGroupAdd(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(),1, mcLen),
                        primaryName,
                        getSecondaryNames()
                );
                break;

            case "groupdel":
            case "群删除":
//                删除服务群
                onGroupDel(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        getSecondaryNames()
                );
                break;

            case "grouplist":
            case "群列表":
//                服务群列表
                onGroupList(
                        commandSender,
                        primaryName,
                        getSecondaryNames()
                );
                break;

            default:
//                不在上述功能内，报告错误
                commandSender.sendMessage("有奇怪的参数，" + commandPrefix + primaryName + "查看帮助");
                return null;
        }


        return null;
    }

    private void onInit(CommandSender commandSender) {
//        数据库初始化操作

        try {
            ReplyListModifier.createAutoReplyDB();

            commandSender.sendMessage("创建数据库完成！");
        } catch (Exception e) {
            commandSender.sendMessage("创建数据库失败，请确保数据库连接地址正确：" + e.toString());
        }

        try {
            ReplyListModifier.createAutoReplyTable();

            commandSender.sendMessage("创建回复数据表完成！");
        } catch (Exception e) {
            commandSender.sendMessage("创建数据表失败：" + e.toString());
        }

        try {
            ServeGroupListModifier.createServeGroupTable();

            commandSender.sendMessage("创建群数据表完成！");
        } catch (Exception e) {
            commandSender.sendMessage("创建数据表失败：" + e.toString());
        }
    }

    public void onSelectAuditingReplies(CommandSender commandSender) {
//        显示待审核列表

        try {
//            交由网页显示
            ReplyWebThread.showAuditingRepliesWeb(commandSender);

//            获取配置文件端口号等参数
            Map<String, String> webMap = ConfigOperation.getWebsiteInifo();
            String host = (String) webMap.get("host");
            int port = Integer.parseInt(webMap.get("port"));

            String res = "点击查看： http://" + host + ":" + port + "\n公用链接，在下一次查询时会覆盖本次内容";
            commandSender.sendMessage(res);
        } catch (Exception e) {
            commandSender.sendMessage("获取失败：" + e.toString());
        }
    }

    private void onDenyReply(CommandSender commandSender, Object[] replyIds, String primaryName, String[] secondaryNames) {
        if (replyIds.length == 0) {
//            未传入回复号，报告错误

            commandSender.sendMessage(OpReplyHelpString.denyHelpStr(primaryName, secondaryNames));
            return;
        }

//        确认回复号都为数字
        Set<Integer> ids = new HashSet<>();

        try {
            for (Object replyId : replyIds) {
                ids.add(Integer.parseInt(replyId.toString()));
            }
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
        }

//        逐条删除回复
        try {
            StringBuilder sb = new StringBuilder();
            for (Integer id : ids) {
                int res = ReplyListModifier.delOneReplyById(id);
                if (res == 0) {
//                    表示没有该条回复，报告错误

                    commandSender.sendMessage("对于回复号为" + id + "的状态修改失败了，可能是不存在该条目或其它意外所致，这些回复号已拒绝完成：" + sb.toString());
                    return;
                }
                sb.append(id).append(" ");
            }
        } catch (Exception e) {
//            不确定的其它错误

            commandSender.sendMessage("奇怪的错误：" + e.toString());
            return;
        }

        commandSender.sendMessage("指定回复已完成拒绝");
    }

    private void onPassReply(CommandSender commandSender, Object[] replyIds, String primaryName, String[] secondaryNames) {

        if (replyIds.length == 0) {
            commandSender.sendMessage(OpReplyHelpString.passHelpStr(primaryName, secondaryNames));
            return;
        }

        Set<Integer> ids = new HashSet<>();

        try {
            for (Object replyId : replyIds) {
                ids.add(Integer.parseInt(replyId.toString()));
            }
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        try {
            StringBuilder sb = new StringBuilder();
            for (Integer id : ids) {
                int res = ReplyListModifier.passReplyById(id);
                if (res == 0) {
                    commandSender.sendMessage("对于回复号为" + id + "的状态修改失败了，可能是不存在该条目或其它意外所致，这些回复号已通过完成：" + sb.toString());
                    return;
                }
                sb.append(id).append(" ");
            }
        } catch (Exception e) {
            commandSender.sendMessage("奇怪的错误：" + e.toString());
            return;
        }

        commandSender.sendMessage("指定回复已完成确认");
    }

    private void onListReplies(CommandSender commandSender, Object[] qqs, String primaryName, String[] secondaryNames) {
        if (qqs.length == 0) {
            try {
                ReplyWebThread.showAllRepliesWeb(commandSender);
                Map<String, String> webMap = ConfigOperation.getWebsiteInifo();
                String host = webMap.get("host");
                int port = Integer.parseInt(webMap.get("port"));

                String res = "点击查看： http://" + host + ":" + port + "\n公用链接，在下一次查询时会覆盖本次内容";
                commandSender.sendMessage(res);
            } catch (Exception e) {
                commandSender.sendMessage("获取失败：" + e.toString());
            }
            return;
        }

        List<Long> qqList = new ArrayList<>();

        try {
            for (Object qq : qqs) {
                qqList.add(Long.parseLong(qq.toString()));
            }
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        try {
            ReplyWebThread.showSelectedUserRepliesWeb(commandSender, qqList);
            Map<String, String> webMap = ConfigOperation.getWebsiteInifo();
            String host = webMap.get("host");
            int port = Integer.parseInt(webMap.get("port"));

            String res = "点击查看： http://" + host + ":" + port + "\n公用链接，在下一次查询时会覆盖本次内容";
            commandSender.sendMessage(res);
        } catch (IOException e) {
            commandSender.sendMessage("获取失败：" + e.toString());
        }
    }

    private void onGroupAdd(CommandSender commandSender, Object[] args, String primaryName, String[] secondaryNames) {
        if (args.length == 0) {
            commandSender.sendMessage(OpReplyHelpString.groupAddHelpStr(primaryName, secondaryNames));
            return;
        }

        Set<Long> groupIds = new HashSet<>();

        try {
            for (Object groupId : args) {
                groupIds.add(Long.parseLong(groupId.toString()));
            }
        } catch (Exception e) {
            commandSender.sendMessage("错误" + e.toString());
        }

        try {
            for (Long groupId : groupIds) {
                int res = ServeGroupListModifier.insertGroupId(groupId);
            }
        } catch (Exception e) {
            commandSender.sendMessage("奇怪的错误：" + e.toString());
            return;
        }

        commandSender.sendMessage("已添加群");
    }

    private void onGroupDel(CommandSender commandSender, Object[] args, String primaryName, String[] secondaryNames) {
        if (args.length == 0) {
            commandSender.sendMessage(OpReplyHelpString.groupDelHelpStr(primaryName, secondaryNames));
            return;
        }

        Set<Long> groupIds = new HashSet<>();

        try {
            for (Object groupId : args) {
                groupIds.add(Long.parseLong(groupId.toString()));
            }
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
        }

        try {
            for (Long groupId : groupIds) {
                int res = ServeGroupListModifier.deleteGroupId(groupId);
            }
        } catch (Exception e) {
            commandSender.sendMessage("奇怪的错误：" + e.toString());
        }

        commandSender.sendMessage("已删除群");
    }

    private void onGroupList(CommandSender commandSender, String primaryName, String[] secondaryNames) {
        try {
            List<Long> groupIds = ServeGroupListModifier.selectAllGroupId();
            StringBuilder sb = new StringBuilder();
            sb.append("已添加群：\n");
            Iterator<Long> iterator = groupIds.iterator();
            while (iterator.hasNext()) {
                sb.append(iterator.next());
                if (iterator.hasNext()) {
                    sb.append("\n");
                }
            }

            commandSender.sendMessage(sb.toString());
        } catch (IOException e) {
            commandSender.sendMessage("奇怪的错误：" + e.toString());
        }
    }
}
